package org.odk.collect.android.activities;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//import com.application.profiler.library.ApplicationMonitor;

public class Prefiller extends Activity {
	static EditText t1;	
	public static String extra;
	public Workbook w = null;
	public Sheet sheet =null;
	 ArrayList<String>[] suggestions ;
	String j;
	String name;
	String url;
	 String j1;
	 String j2;
	 String fName;
	 String aFinal;
	 String dispName;
     ArrayList<Integer> nums;
	  
    @Override
    public void onCreate(Bundle savedInstanceState) {
    //	ApplicationMonitor monitor= new ApplicationMonitor(this);
 //  	monitor.markAsResourceIntensive(3);
    
   	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.prefiller);
        
        Intent intent = getIntent();
		 extra = intent.getStringExtra("extra");
		 fName = intent.getStringExtra("name");
		 aFinal =intent.getStringExtra("string1");
	
//TextView tv;
//tv = (TextView)findViewById(R.id.changefilter);

//Button button;
//button = (Button) findViewById(R.id.create_prefilled_forms_in_range);


//t1 = (EditText) findViewById(R.id.startfill);
		
System.out.println("Extra is"+extra);


	SQLiteOpenHelper mDbHelper = null;
	 SQLiteDatabase mDb1 = null;
  mDbHelper = new SQLiteOpenHelper(Collect.METADATA_PATH, "forms.db", null);
  mDb1 = mDbHelper.getReadableDatabase(); 
  
  String [] displayName = new String[1];
  Cursor c =mDb1.query("forms", null	, "_id" + "='" + extra + "'", null, null, null, null);
 
  if (c != null ) {
      if  (c.moveToFirst()) {
           j = c.getString(c.getColumnIndex("displayName"));
           name =j;
           url = c.getString(c.getColumnIndex("submissionUri"));
           j=j.replace(".", " ");
         
           j1 = c.getString(c.getColumnIndex("jrFormId"));

           j2 = c.getString(c.getColumnIndex("formFilePath"));

          System.out.println("---- value of j is :"+j);
          System.out.println(j1);
          System.out.println(j2);

      }   
  }
  
 
  
      try {
    		 File sdCard = Environment.getExternalStorageDirectory();

  		File dir1 = new File(sdCard.getAbsolutePath() + "/odk/forms/"+j+"-media/"+fName);

			try {
				w = Workbook.getWorkbook(dir1);
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
      // Get the first sheet
        sheet = w.getSheet(2);
ArrayList<String>questions = new ArrayList<String>();
ArrayList<String> filters = new ArrayList<String>();
      for (int j = 0; j <= 1; j++) {
          for (int i = 1; i < sheet.getRows(); i++) {
              Cell cell = sheet.getCell(j, i);
              CellType type = cell.getType();
              if (cell.getType() == CellType.LABEL) {
                  System.out.println("I got a label "
                          + cell.getContents());
                  String number = cell.getContents();
                  if(j==0){
                  filters.add(number);
                  }
                  	if(j==1)
                  	{
      				questions.add(number);
                  	}
                     	                   } 
              }
      }
      
      System.out.println("filters are" + filters+"\n \n");
     nums = new ArrayList<Integer>();
      try{
      sheet = w.getSheet(0);

      for(String e : filters)
      {
          for (int i = 1; i < sheet.getColumns(); i++) {
        	  Cell cell = sheet.getCell( i,0);
        	  if(cell.getContents().equals(e)){nums.add(i);}
        	  
          }
         
      }
      System.out.println(nums);
      
     suggestions = (ArrayList<String>[])new ArrayList[filters.size()];
int k =0;
      
      for(int e: nums){
    	  ArrayList<String> options = new ArrayList<String>();
    	   for (int i = 1; i < sheet.getRows(); i++) {
         	  Cell cell = sheet.getCell( e,i);
         	  options.add(cell.getContents());

    	   }  
    	   Set<String> name = new HashSet<String>();
    	   name.addAll(options);
    	   options.clear();
    	   options.addAll(name);
    	   System.out.println("column"+e+options);
           suggestions[k] =options;
           k++;

      }
      }
      
      catch(Exception e){}
     
     
      final int N = questions.size(); // total number of textviews to add

      final TextView[] myTextViews = new TextView[N]; // create an empty array;
      final EditText[] myeditTexts = new EditText[N]; // create an empty array;
      
      
      
      for (int i = 0; i < N; i++) {
          // create a new textview
          final TextView tv = new TextView(this);
          final AutoCompleteTextView  e1 = new AutoCompleteTextView (this);
          
          LayoutParams lparams = new LayoutParams(
       		   LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
          // set some properties of rowTextView or something
          tv.setText(questions.get(i));
          tv.setLayoutParams(lparams);
          
         e1.setLayoutParams(lparams);
         
         
         ArrayAdapter<String> adapter = 
     	        new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, suggestions[i]);
     	e1.setAdapter(adapter);

     	
     	LinearLayout layout = (LinearLayout) findViewById(R.id.rl);
         
          layout.addView(tv);
          layout.addView(e1);
          // save a reference to the textview for later
          myTextViews[i] = tv;
          myeditTexts[i]=e1;
          
        
      }
      final Button button = new Button(this);
      LayoutParams lparams = new LayoutParams(
      		   LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
      LinearLayout layout = (LinearLayout) findViewById(R.id.rl);
      button.setText("Create Prefilled Form");
      layout.addView(button);
  //parent.addView(layout);
  
  
  
  
		//tv.setText("Enter Panchayat");
    		//t1.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

		
		
		
		
		//Button button;
		//button = (Button) findViewById(R.id.create_prefilled_forms_in_range);
		
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	
            	String start = name;
            	/*
            	for(int y=0;y<N;y++)
            	{
            		 start=myeditTexts[y].getText().toString();
            	}*/
   	
	{
	
        Sheet sheet0 = w.getSheet(0);
        Sheet sheet2 =w.getSheet(1);
        
        int rows2 = sheet2.getRows();
        int rows = sheet.getRows();
        ArrayList<String> excelName = new ArrayList<String>();
        ArrayList<String> formName = new ArrayList<String>();
        HashMap<String,Integer> col =new HashMap<String,Integer>();
        ArrayList<Integer> col_filter = new ArrayList<Integer>();
        for(int i=1;i<rows;i++)
        {
        	 Cell cell = sheet.getCell(0, i);
        	for(int k=0;k<sheet0.getColumns();k++)
        	{
        		Cell cell2 = sheet0.getCell(k, 0);
        		if(cell.getContents().equalsIgnoreCase(cell2.getContents()))
        		{
        			col_filter.add(k);
        			System.out.println("added"+k);
        			break;
        		}
        	}
        }
        col_filter.addAll(nums);
        System.out.println("Column filter is"+col_filter);
        
        
        
        
        for(int i=1;i<rows2;i++)
        {
     	   for(int j=0;j<2;j++)
     	   {
     		   
     		   if(j==0)
     		   {
     			   Cell cell2 = sheet2.getCell(j, i);
         		   excelName.add(cell2.getContents());
     			   for(int k=0;k<sheet0.getColumns();k++)
     			   {
     				   Cell cell3 = sheet0.getCell(k, 0);
     				   if(cell3.getContents().equalsIgnoreCase(cell2.getContents()))
     				   {
     					   col.put(cell2.getContents(), k);
     					   break;
     				   }
     			   }
     		   }
     		   else
     		   {
     			   Cell cell2 = sheet2.getCell(j, i);
         		   formName.add(cell2.getContents());
     		   }
     			
     	   }
        }
       if(col.size()!=excelName.size())
       {
     	  System.out.println("Error in the excelSheet names");
       }
       else if(excelName.size()!=formName.size())
       {
     	  System.out.println("Mismatch in no. of names of excel and form");
       }
  

       
      
            int count=0;
            for (int i = 0; i < sheet0.getRows(); i++) {
            	int flag1=1;
            	for( int q= 0; q<col_filter.size();q++)
            	{
            		Cell cell = sheet0.getCell(col_filter.get(q), i);
            		if(!(myeditTexts[q].getText().toString().equalsIgnoreCase(cell.getContents())))
            		{
            			flag1=0;
            			break;
            		}
            	}
                
                    if(flag1==1)
                    {
                    	
                    	int flag2=0;
        				if(count==0)
        				{
        				  for(int l=0;l<excelName.size();l++)
        				  {
        					  System.out.println("excel name:"+ excelName.get(l));
        					  System.out.println("form name:"+ formName.get(l));
        					  System.out.println("mapped value:"+col.get(excelName.get(l)) );
        					  System.out.println(sheet0.getCell(col.get(excelName.get(l)),i).getContents());
        					  aFinal=aFinal.replace("<"+formName.get(l)+"/>","<"+formName.get(l)+">"+sheet0.getCell(col.get(excelName.get(l)),i).getContents()+"</"+formName.get(l)+">");
        					  if(formName.get(l).equalsIgnoreCase("form_name"))
        					  {
        						  dispName=sheet0.getCell(col.get(excelName.get(l)),i).getContents();
        						  flag2=1;
        					  }
        				  }
        				  if(flag2==0)
        				  {
        					  dispName=name;
        				  }
        				  count++;
        				}
        				else
        				{
        					 
        					for(int l=0;l<excelName.size();l++)
           				  {
        					
       					  String temp1 = "<"+formName.get(l)+">";
       		     		  String temp2 = "</"+formName.get(l)+">";
       					  int startIndex = aFinal.indexOf(temp1);
       					  int endIndex = aFinal.indexOf(temp2);
       					  int len2 = temp2.length();
       					  String temp3 = aFinal.substring(startIndex, endIndex+len2);
       					  System.out.println(sheet0.getCell(col.get(excelName.get(l)),i).getContents());
       					  String temp4 = temp1+sheet0.getCell(col.get(excelName.get(l)),i).getContents()+temp2;
       					  aFinal =aFinal.replace(temp3, temp4);
       					 if(formName.get(l).equalsIgnoreCase("form_name"))
   					  {
   						  dispName=sheet0.getCell(col.get(excelName.get(l)),i).getContents();
   						  flag2=1;
   					  }
       				      
           				  }
        					if(flag2==0)
          				  {
          					  dispName=name;
          				  }
        					 count++;
        				}
        				if(aFinal.indexOf("<prefill_not/>")!=-1)
        				{
        					aFinal=aFinal.replace("<prefill_not/>", "<prefill_not>"+"Prefilled Form"+"</prefill_not>");
        				}
        				/*
        			   	 aFinal=aFinal.replace("<head_family/>","<head_family>"+head+"</head_family>");
        				 aFinal=aFinal.replace("<no_male/>","<no_male>"+male+"</no_male>");
        				 aFinal=aFinal.replace("<no_female/>","<no_female>"+female+"</no_female>");
        				 aFinal=aFinal.replace("<no_disabled/>","<no_disabled>"+disabled+"</no_disabled>");
        				 aFinal=aFinal.replace("<no_SHG/>","<no_SHG>"+shg+"</no_SHG>");
        				 aFinal=aFinal.replace("<Panchayat/>","<Panchayat>"+panchayat+"</Panchayat>");
        				 aFinal=aFinal.replace("<Village/>","<Village>"+village+"</Village>");
        				 aFinal=aFinal.replace("<nrega_no/>","<nrega_no>"+jobId+"</nrega_no>");
        				 */
        				 //aFinal=aFinal.replace("<instanceID/>","<instanceID>"+"uuid:5a0e322f-8630-4cdc-a4b6-77f10246c7d7"+"</instanceID>");
        				 
        				// aFinal = aFinal.replaceAll("/>", " />");
        				 //aFinal = aFinal.replace("?>", " ?>");
        				 //aFinal = aFinal.replace("xml version=\"1.0\"", "xml version=\'1.0\'");
        				
        				 
        				
        				System.out.println("-------------------------------------------------");
        				//System.out.println(aFinal);    
        				 String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.ENGLISH).format(Calendar.getInstance()
        		                    .getTime());
        				String fdir ="/mnt/sdcard/odk/instances/"+start+count+ "_"+time;//---------------
        				String fname="/mnt/sdcard/odk/instances/"+start+count+ "_"+time+"/"+start+count+ "_"+time+".xml";//------------
        				Boolean bool = new File(fdir).mkdirs();
        				 File file1 = new File(fname);
        				 
        				FileWriter fileWriter = null;
        					try {
        						fileWriter = new FileWriter(file1);
        						fileWriter.write(aFinal);
        						 fileWriter.close();
        					} catch (IOException e1) {
        						// TODO Auto-generated catch block
        						e1.printStackTrace();
        					}
                    	
        					SQLiteOpenHelper mDbHelper = null;
                       	 SQLiteDatabase mDb = null;
                           mDbHelper = new SQLiteOpenHelper(Collect.METADATA_PATH, "instances.db", null);
                           mDb = mDbHelper.getWritableDatabase(); 
                           
                            
                            final String ipath = "instanceFilePath";
                           ContentValues cv = new ContentValues();
                       	cv.put("displayName",dispName);

                       	cv.put("submissionUri",url);//--------------
                       	// 
                      // 	cv.put("instanceFilePath","/mnt/sdcard/odk/instances/"+start+count+"/"+start+count+".xml");//------
                       	cv.put("instanceFilePath","/mnt/sdcard/odk/instances/"+start+count+ "_"+time+"/"+start+count+ "_"+time+".xml");
                       	cv.put("jrFormId",j1);

                       	//cv.put("jrVersion",null);

                       	cv.put("status","incomplete");

                       	cv.put("canEditWhenComplete","true");
                       	Long now = Long.valueOf(System.currentTimeMillis());
                       	cv.put("date",now);
                        Date today = new Date();

                        String ts = new SimpleDateFormat(Prefiller.this.getApplicationContext().getString(R.string.saved_on_date_at_time), Locale.getDefault()).format(today);
                       	cv.put("displaySubtext",ts);
                       	
                       	


                                           	
                       	mDb.insert("instances", null, cv);
                       	
                       	
                    mDb.close();
                       	
                       	
        					
        					
                    	
                    
                   
                }

               

            }
      //  }
       
   // }
      System.out.println("Count is :" + count);
    //display in short period of time
      Toast.makeText(getApplicationContext(), count +" prefililled forms sucessfully created", Toast.LENGTH_SHORT).show();
	    Intent i = new Intent(getApplicationContext(), MainMenuActivity.class);
    startActivity(i);
}

            	
            }
        });
		

    }

   

    
}
